import React, { useState, useEffect, useRef, useCallback } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Card, Select, DatePicker, Row, Col, Statistic, Spin, message, Button, Space } from 'antd';
import { ArrowUpOutlined, ArrowDownOutlined, ReloadOutlined } from '@ant-design/icons';
import * as echarts from 'echarts';
import { dataService } from '../../services/dataService';
import type { ChartListItem, ChartDataParams, ChartDataResponse, SummaryDataResponse } from '../../services/dataService';
import dayjs from 'dayjs';

const { RangePicker } = DatePicker;
const { Option } = Select;

type TimeRangeType = 'recent7' | 'recent30' | 'current_week' | 'current_month' | 'custom';

const DataOverview: React.FC = () => {
    const chartRef = useRef<echarts.ECharts | null>(null);
    const chartContainerRef = useRef<HTMLDivElement>(null);
    const resizeObserverRef = useRef<ResizeObserver | null>(null);

    // 状态管理
    const [chartList, setChartList] = useState<ChartListItem[]>([]);
    const [selectedChart, setSelectedChart] = useState<string>('');
    const [timeRange, setTimeRange] = useState<[dayjs.Dayjs, dayjs.Dayjs] | null>(null);
    const [timeRangeType, setTimeRangeType] = useState<TimeRangeType>('recent7');
    const [loading, setLoading] = useState(false);
    const [chartData, setChartData] = useState<ChartDataResponse | null>(null);
    const [summaryData, setSummaryData] = useState<SummaryDataResponse['summary'] | null>(null);

    // 初始化图表
    const initChart = useCallback((): echarts.ECharts | null => {
        if (!chartContainerRef.current) {
            console.warn('图表容器DOM元素不存在');
            return null;
        }

        try {
            // 先销毁现有实例
            if (chartRef.current) {
                chartRef.current.dispose();
                chartRef.current = null;
            }

            const chart = echarts.init(chartContainerRef.current);
            chartRef.current = chart;
            console.log('图表初始化成功');
            return chart;
        } catch (error) {
            console.error('图表初始化失败:', error);
            return null;
        }
    }, []);

    // 销毁图表
    const destroyChart = useCallback(() => {
        if (chartRef.current) {
            try {
                chartRef.current.dispose();
                chartRef.current = null;
                console.log('图表销毁成功');
            } catch (error) {
                console.error('图表销毁失败:', error);
            }
        }
    }, []);

    // 渲染图表（销毁后重新创建）
    const renderChart = useCallback((data: ChartDataResponse) => {
        if (!chartContainerRef.current || !data) {
            console.warn('容器不存在或数据为空');
            return;
        }

        // 销毁现有图表
        destroyChart();

        // 重新初始化
        const chart = initChart();
        if (!chart) {
            console.error('图表初始化失败');
            return;
        }

        const option = {
            title: {
                text: data.title,
                subtext: data.subtitle,
                left: 'center'
            },
            tooltip: {
                trigger: 'axis',
                formatter: (params: any) => {
                    const item = params[0];
                    const unit = data.meta[data.yField]?.unit || '';
                    return `${item.name}<br/>${item.seriesName}: ${item.value}${unit}`;
                }
            },
            legend: {
                data: [data.meta[data.yField]?.alias || data.yField],
                bottom: 10
            },
            grid: {
                left: '60px',
                right: '40px',
                bottom: '60px',
                top: '80px'
            },
            xAxis: {
                type: 'category',
                data: data.data.map(item => item[data.xField])
            },
            yAxis: {
                type: 'value',
                name: data.meta[data.yField]?.alias || data.yField
            },
            series: [{
                name: data.meta[data.yField]?.alias || data.yField,
                type: 'line',
                smooth: true,
                areaStyle: { opacity: 0.3 },
                data: data.data.map(item => Number(item[data.yField]) || 0)
            }]
        };

        try {
            chart.setOption(option);
            // 确保图表尺寸正确
            setTimeout(() => {
                if (chart) {
                    chart.resize();
                }
            }, 100);
            console.log('图表渲染成功');
        } catch (error) {
            console.error('图表渲染失败:', error);
        }
    }, [destroyChart, initChart]);

    // 设置容器尺寸监听
    const setupResizeObserver = useCallback(() => {
        if (!chartContainerRef.current || typeof ResizeObserver === 'undefined') {
            return;
        }

        // 清理旧的观察者
        if (resizeObserverRef.current) {
            resizeObserverRef.current.disconnect();
        }

        resizeObserverRef.current = new ResizeObserver(() => {
            if (chartRef.current) {
                chartRef.current.resize();
            }
        });

        resizeObserverRef.current.observe(chartContainerRef.current);
    }, []);

    // 获取数据
    const loadData = async () => {
        if (!selectedChart || !timeRange) return;

        setLoading(true);
        try {
            const params: ChartDataParams = {
                store: 1,
                chartId: selectedChart,
                timeRangeStart: timeRange[0].format('YYYY-MM-DD'),
                timeRangeEnd: timeRange[1].format('YYYY-MM-DD'),
                limit: 100
            };

            const [chartResponse, summaryResponse] = await Promise.all([
                dataService.getChartData(params),
                dataService.getSummaryData(params)
            ]);
            console.log('chartResponse', chartResponse);
            console.log('summaryResponse', summaryResponse);

            if (chartResponse.code === 0 && chartResponse.data) {
                setChartData(chartResponse.data);
            }

            if (summaryResponse.code === 0 && summaryResponse.data) {
                setSummaryData(summaryResponse.data.summary);
            }
        } catch (error) {
            console.error('获取数据失败:', error);
            message.error('获取数据失败');
        } finally {
            setLoading(false);
        }
    };

    // 获取图表列表
    const loadChartList = async () => {
        try {
            const response = await dataService.getChartList();
            if (response.code === 0 && response.data) {
                setChartList(response.data);
                if (response.data.length > 0) {
                    setSelectedChart(response.data[0].id);
                }
            }
        } catch (error) {
            message.error('获取图表列表失败');
        }
    };

    // 处理时间范围切换
    const handleTimeRangeChange = (type: TimeRangeType) => {
        setTimeRangeType(type);

        if (type === 'recent7') {
            setTimeRange([dayjs().subtract(6, 'day'), dayjs()]);
        } else if (type === 'recent30') {
            setTimeRange([dayjs().subtract(1, 'month'), dayjs()]);
        } else if (type === 'current_week') {
            // 本周：从本周一到今天
            const startOfWeek = dayjs().startOf('week'); // 本周一
            setTimeRange([startOfWeek, dayjs()]);
        } else if (type === 'current_month') {
            // 本月：从本月1号到今天
            const startOfMonth = dayjs().startOf('month');
            setTimeRange([startOfMonth, dayjs()]);
        }
    };

    // 处理自定义时间范围
    const handleCustomTimeChange = (dates: [dayjs.Dayjs, dayjs.Dayjs] | null) => {
        setTimeRange(dates);
        if (dates) {
            setTimeRangeType('custom');
        }
    };

    // 获取时间范围显示文本
    const getTimeRangeText = () => {
        if (!timeRange) return '';

        if (timeRangeType === 'recent7') return '最近7天';
        if (timeRangeType === 'recent30') return '最近30天';
        if (timeRangeType === 'current_week') return '本周';
        if (timeRangeType === 'current_month') return '本月';

        return `${timeRange[0].format('MM-DD')} 至 ${timeRange[1].format('MM-DD')}`;
    };

    // 当数据变化时重新渲染图表
    useEffect(() => {
        if (chartData && chartContainerRef.current) {
            // 延迟渲染确保DOM完全就绪
            const timer = setTimeout(() => {
                renderChart(chartData);
                // 设置尺寸监听
                setupResizeObserver();
            }, 300);

            return () => {
                clearTimeout(timer);
            };
        }
    }, [chartData, renderChart, setupResizeObserver]);

    // 组件初始化
    useEffect(() => {
        loadChartList();
        handleTimeRangeChange('recent7'); // 设置默认时间范围
    }, []);

    // 当图表或时间范围变化时加载数据
    useEffect(() => {
        if (selectedChart && timeRange) {
            loadData();
        }
    }, [selectedChart, timeRange]);

    // 清理资源
    useEffect(() => {
        return () => {
            // 清理ResizeObserver
            if (resizeObserverRef.current) {
                resizeObserverRef.current.disconnect();
                resizeObserverRef.current = null;
            }

            // 清理图表实例
            destroyChart();
        };
    }, [destroyChart]);

    return (
        <PageContainer
            title="数据概览"
            subTitle={timeRange ? getTimeRangeText() : ''}
            extra={[
                <Select
                    key="chart-select"
                    placeholder="选择图表"
                    value={selectedChart}
                    onChange={setSelectedChart}
                    style={{ width: 180 }}
                >
                    {chartList.map(chart => (
                        <Option key={chart.id} value={chart.id}>
                            {chart.title}
                        </Option>
                    ))}
                </Select>,
                <Space.Compact key="time-range-buttons">
                    <Button
                        type={timeRangeType === 'recent7' ? 'primary' : 'default'}
                        onClick={() => handleTimeRangeChange('recent7')}
                        size="small"
                    >
                        最近7天
                    </Button>
                    <Button
                        type={timeRangeType === 'recent30' ? 'primary' : 'default'}
                        onClick={() => handleTimeRangeChange('recent30')}
                        size="small"
                    >
                        最近30天
                    </Button>
                    <Button
                        type={timeRangeType === 'current_week' ? 'primary' : 'default'}
                        onClick={() => handleTimeRangeChange('current_week')}
                        size="small"
                    >
                        本周
                    </Button>
                    <Button
                        type={timeRangeType === 'current_month' ? 'primary' : 'default'}
                        onClick={() => handleTimeRangeChange('current_month')}
                        size="small"
                    >
                        本月
                    </Button>
                    <Button
                        type={timeRangeType === 'custom' ? 'primary' : 'default'}
                        onClick={() => handleTimeRangeChange('custom')}
                        size="small"
                    >
                        自定义
                    </Button>
                </Space.Compact>,
                <Button
                    key="refresh"
                    icon={<ReloadOutlined />}
                    onClick={loadData}
                    size="small"
                >
                    刷新
                </Button>
            ]}
        >
            {timeRangeType === 'custom' && (
                <div style={{ marginBottom: 16 }}>
                    <RangePicker
                        value={timeRange}
                        onChange={(dates) => handleCustomTimeChange(dates as [dayjs.Dayjs, dayjs.Dayjs] | null)}
                        placeholder={['开始日期', '结束日期']}
                        size="small"
                        style={{ width: 300 }}
                    />
                </div>
            )}

            {loading ? (
                <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: 300 }}>
                    <Spin size="large" />
                </div>
            ) : (
                <>
                    {summaryData && (
                        <Row gutter={16} style={{ marginBottom: 24 }}>
                            <Col span={8}>
                                <Card>
                                    <Statistic
                                        title={summaryData.meta.gmv?.alias || 'GMV'}
                                        value={Number(summaryData.gmv)?.toFixed(2) || 0}
                                        suffix={summaryData.unit}
                                        valueStyle={{ color: '#3f8600' }}
                                    />
                                </Card>
                            </Col>
                            <Col span={8}>
                                <Card>
                                    <Statistic
                                        title={summaryData.meta.rate?.alias || '环比'}
                                        value={summaryData.rate}
                                        precision={2}
                                        valueStyle={{ color: summaryData.rate > 0 ? '#3f8600' : '#cf1322' }}
                                        prefix={summaryData.rate > 0 ? <ArrowUpOutlined /> : <ArrowDownOutlined />}
                                        suffix={summaryData.meta.rate?.unit || '%'}
                                    />
                                </Card>
                            </Col>
                            <Col span={8}>
                                <Card>
                                    <Statistic
                                        title={summaryData.meta.same_rate?.alias || '同比'}
                                        value={summaryData.same_rate}
                                        precision={2}
                                        valueStyle={{ color: summaryData.same_rate > 0 ? '#3f8600' : '#cf1322' }}
                                        prefix={summaryData.same_rate > 0 ? <ArrowUpOutlined /> : <ArrowDownOutlined />}
                                        suffix={summaryData.meta.same_rate?.unit || '%'}
                                    />
                                </Card>
                            </Col>
                        </Row>
                    )}

                    <Card>
                        <div
                            ref={chartContainerRef}
                            style={{ width: '100%', height: '400px' }}
                        />
                    </Card>
                </>
            )}
        </PageContainer>
    );
};

export default DataOverview;
